package com.shangyitong.yygh_sms.controller;

import com.shangyitong.Result;
import com.shangyitong.ResultCodeEnum;
import com.shangyitong.yygh_sms.service.SmsService;
import com.shangyitong.yygh_sms.smsutils.RandomUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/rly")
@Slf4j
public class SmsController {
    @Autowired
    private SmsService smsService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    //发送手机验证码
    @GetMapping("send/{phone}")
    public Result sendCode(@PathVariable String phone) {
        //获取redis中的code
        String code = stringRedisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)) {
            return Result.ok(code);
        }
        code = RandomUtils.getSixBitRandom();
        boolean isSend = smsService.send(phone, code);
        if (isSend) {
            stringRedisTemplate.opsForValue().set(phone,code,2, TimeUnit.MINUTES);
            return Result.ok();
        }
        return Result.fail().message("短信发送失败");
    }
}


